<template>
  <div>
    <input type="text" v-model="message" placeholder="输入要发布的消息" />
    <button @click="publishMessage">发布</button>
    <div>
      <h3>接收到的消息：</h3>
      <p>{{ receivedMessage }}</p>
    </div>
  </div>
</template>

<script setup lang='ts'>
import { ref, onMounted, onUnmounted ,onBeforeUnmount} from 'vue';
import { Client } from 'paho-mqtt';
const client = ref(null);
const message = ref('');
const receivedMessage = ref('');

const onConnect = () => {
  console.log('MQTT connected');
  client.value.subscribe('topic'); // 订阅消息的主题
};

const onMessageArrived = (msg) => {
  receivedMessage.value = msg.payloadString;
  console.log('Received message:', receivedMessage.value);
};

const publishMessage = () => {
  if (client.value.isConnected()) {
    const messagePayload = new Paho.MQTT.Message(message.value);
    messagePayload.destinationName = 'topic'; // 发布消息的主题
    client.value.send(messagePayload);
  } else {
    console.log('MQTT client is not connected.');
  }
};

onMounted(() => {
  client.value = new Client('broker.hivemq.com', 8000, 'clientId');
  client.value.onConnectionLost = (err) => {
    console.log('MQTT connection lost:',err, err.errorMessage);
  };
  client.value.onMessageArrived = onMessageArrived;

  client.value.connect({
    onSuccess: onConnect,
    useSSL: false,
  });
});

onBeforeUnmount(() => {
      if (client.value && client.value.isConnected()) {
        client.value.disconnect();
      }
    });


</script>

<style scoped></style>